package com.sinodata.bsm.cicp.collector.tomcat;

import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class MemoryCollector extends Collector {
    private static Logger logger = Logger.getLogger(MemoryCollector.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String[] result = new String[5];
        //        String port = this.getParamMap().get("端口");
        String port = this.getParamMap().get("Port");
        String[] propertyNames = new String[] { "Name", "Type" };
        Object propertyValues[] = null;
        //        String name = this.getParamMap().get("名称").trim();
        String name = this.getParamMap().get("Name").trim();

        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            //connector = JmxUtil.getConnection(JmxUtil.TOMCAT, ip + ":" + port);
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            ObjectName memoryPool = new ObjectName("java.lang:type=MemoryPool,*");
            Set<ObjectName> set = connection.queryNames(memoryPool, null);
            for (ObjectName objectName : set) {
                propertyValues = JmxUtil.getAttribute(connection, objectName, propertyNames);
                if (propertyValues[0].toString().equals(name)) {
                    result[0] = propertyValues[1].toString();
                    MemoryUsage heapMemoryUsage = MemoryUsage.from((CompositeDataSupport) connection.getAttribute(objectName, "Usage"));
                    if (heapMemoryUsage != null) {
                        result[1] = "" + heapMemoryUsage.getUsed();
                        result[2] = "" + heapMemoryUsage.getCommitted();
                        result[3] = "" + heapMemoryUsage.getMax();
                        if (heapMemoryUsage.getMax() > 0) {
                            result[4] = "" + heapMemoryUsage.getUsed() * 100 / Double.parseDouble(heapMemoryUsage.getMax() + "");
                        } else {
                            result[4] = "0";
                        }
                    } else {
                        result[1] = "0";
                        result[2] = "0";
                        result[3] = "0";
                        result[4] = "0";
                    }
                    for (int i = 0; i < result.length; i++) {
                        propValues[i] = ResPropertyValue.createPropValue(result[i].toString(), propMetas[i]);

                    }
                }
            }
        } catch (Exception e) {
            logger.error("when MemoryCollector" + e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
        propertyValueX.setValues(propValues);
        values.add(propertyValueX);
        return values;
    }

    @Override
    public String[] getParamMeta() {
        //        return new String[] { "名称", "端口" };
        return new String[] { "Name", "Port" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "类型", "已使用", "已分配", "最大", "使用率" };
        return new String[] { "$1", "$2", "$3", "$4", "$5" };
    }
}
